package jdbc.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA
 * Description:Druid学习
 * User:22954
 * Date:2024-05-22
 * Time:7:04
 */
public class Druid_ {
    @Test
    public void druid() throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src/jdbc/datasource/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            Connection connection = dataSource.getConnection();
//            System.out.println("Success");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("Druid连接池耗时:" + (end - start));//Druid连接池耗时:292
    }

    @Test
    public void druidByUtil() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String sql = "select * from `admin` where `name` = ?";
        try {
            connection = JDBCUtilByDruid.getConnection();
            System.out.println(connection.getClass());//class com.alibaba.druid.pool.DruidPooledConnection
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "tom");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString(1);
                String password = resultSet.getString(2);
                System.out.println("name:" + name + "\tpassword:" + password);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilByDruid.close(resultSet,preparedStatement,connection);
        }

    }
}
